import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:intl/intl.dart';
import '../models/smoking_record.dart';
import '../services/storage_service.dart';

class CalendarPage extends StatefulWidget {
  const CalendarPage({super.key});

  @override
  State<CalendarPage> createState() => _CalendarPageState();
}

class _CalendarPageState extends State<CalendarPage> {
  final StorageService _storageService = StorageService();
  CalendarFormat _calendarFormat = CalendarFormat.month;
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  Map<DateTime, int> _recordCounts = {};
  List<SmokingRecord> _selectedDayRecords = [];

  @override
  void initState() {
    super.initState();
    _selectedDay = _focusedDay;
    _loadRecordCounts();
    _loadSelectedDayRecords();
  }

  // 加载所有日期的记录计数
  Future<void> _loadRecordCounts() async {
    final counts = await _storageService.getRecordCountsByDate();
    setState(() {
      _recordCounts = counts;
    });
  }

  // 加载选定日期的详细记录
  Future<void> _loadSelectedDayRecords() async {
    if (_selectedDay != null) {
      final records = await _storageService.getRecordsForDate(_selectedDay!);
      setState(() {
        _selectedDayRecords = records;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('抽烟记录日历'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Column(
        children: [
          TableCalendar(
            firstDay: DateTime.utc(2020, 1, 1),
            lastDay: DateTime.utc(2030, 12, 31),
            focusedDay: _focusedDay,
            calendarFormat: _calendarFormat,
            eventLoader: (day) {
              // 获取该日期的事件（抽烟记录数量）
              final normalizedDay = DateTime(day.year, day.month, day.day);
              final count = _recordCounts[normalizedDay] ?? 0;
              return count > 0 ? [count] : [];
            },
            selectedDayPredicate: (day) {
              return isSameDay(_selectedDay, day);
            },
            onDaySelected: (selectedDay, focusedDay) {
              setState(() {
                _selectedDay = selectedDay;
                _focusedDay = focusedDay;
              });
              _loadSelectedDayRecords();
            },
            onFormatChanged: (format) {
              setState(() {
                _calendarFormat = format;
              });
            },
            onPageChanged: (focusedDay) {
              _focusedDay = focusedDay;
            },
            calendarBuilders: CalendarBuilders(
              markerBuilder: (context, date, events) {
                if (events.isNotEmpty) {
                  return Positioned(
                    right: 1,
                    bottom: 1,
                    child: Container(
                      padding: const EdgeInsets.all(2),
                      decoration: const BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.red,
                      ),
                      child: Text(
                        '${events[0]}',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                        ),
                      ),
                    ),
                  );
                }
                return null;
              },
            ),
          ),
          const Divider(),
          Expanded(
            child: _buildRecordsList(),
          ),
        ],
      ),
    );
  }

  Widget _buildRecordsList() {
    if (_selectedDayRecords.isEmpty) {
      return const Center(
        child: Text('今天没有抽烟记录'),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Text(
            '${DateFormat('yyyy年MM月dd日').format(_selectedDay!)} - 共抽了 ${_selectedDayRecords.length} 根',
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _selectedDayRecords.length,
            itemBuilder: (context, index) {
              final record = _selectedDayRecords[index];
              return ListTile(
                leading: const Icon(Icons.smoking_rooms, color: Colors.red),
                title: Text('第 ${index + 1} 根'),
                subtitle: Text('时间: ${record.getFormattedTime()}'),
              );
            },
          ),
        ),
      ],
    );
  }
} 